/*
 * 资料修改模块样式
 * 2018年3月21日16:54:59
 * xwx
 */

(function() {

	var userinfo = server.user.getLoginUser();
	var userinfoobj;
	var wait; //加载动画
	var deptArry = []; //所在部门数组对象
	var partyDeptArry = []; //所在支部数组对象
	var deptArryPicker = new mui.PopPicker();
	var partyDeptPicker = new mui.PopPicker();
	var deptResult = document.getElementById('dept');
	var partyDeptResult = document.getElementById('partyDept');

	//	初始化资料数据
	var w = new Vue({
		el: '#userInfo',
		data: userinfoobj = {
			userinfo: userinfo
		}
	});

	getDeps();
	initEvt();
	document.getElementById('dept').value = userinfo.deptName;
	document.getElementById('partyDept').value = userinfo.partyDeptName;

	//	初始化事件
	function initEvt() {

		//	所在部门筛选
		$("body").on('tap', '.mui-input-row #dept', function() {
			deptArryPicker.setData(deptArry);
			var deptResultText = document.getElementById('dept');
			deptArryPicker.show(function(items) {
				deptResultText.value = items[0].text;
				userinfo.dept = items[0].value; //设置房间id
			});
		});

		//	所在支部筛选
		mui("body").on("tap", ".mui-input-row #partyDept", function(e) {
			partyDeptPicker.setData(partyDeptArry);
			var partyDeptResultText = document.getElementById('partyDept');
			partyDeptPicker.show(function(items) {
				partyDeptResultText.value = items[0].text;
				userinfo.partyDept = items[0].value; //设置房间id
			});
		});

	}

	//	获取所在部门、所在支部信息
	function getDeps() {

		deptArry = []; //所在部门数组对象
		partyDeptArry = []; //所在支部数组对象

		//	获取所在部门信息
		server.user.getDeparInfo(1, function(r) {
			if(r.errCode == 0) {
				var tempArry = [];
				if(r.data.length > 0) {
					var temp = [];
					for(var i = 0; i < r.data.length; i++) {
						temp = {
							"value": r.data[i].id,
							"text": r.data[i].name
						};
						tempArry.push(temp);
					}
				} else { //暂无部门时处理

				}

				deptArry = tempArry;
			}
		}, function(r) {
			mui.toast("服务器错误，请稍后刷新重试");
		});

		//	获取所在支部信息
		server.user.getDeparInfo(2, function(r) {
			if(r.errCode == 0) {
				var tempArry = [];
				if(r.data.length > 0) {
					var temp = [];
					for(var i = 0; i < r.data.length; i++) {
						temp = {
							"value": r.data[i].id,
							"text": r.data[i].name
						};
						tempArry.push(temp);
					}
				} else { //暂无部门时处理

				}

				partyDeptArry = tempArry;
			}
		}, function(r) {
			mui.toast("服务器错误，请稍后刷新重试");
		});

	}

	var avatar = document.getElementById('head-img1');
	var image = document.getElementById('image');
	var input = document.getElementById('headinput');
	var $modal = $('#modal');
	var cropper;

	//	保存更新资料
	mui('body').on('tap', '#btnModify', function() {
		updataInfo();
	});

	//	更换头像操作
	mui(".mui-table-view-cell").on("tap", "#head", function(e) {
		if(mui.os.plus) {
			var upts = [{
				title: "拍照"
			}, {
				title: "从相册中选择"
			}];
			plus.nativeUI.actionSheet({
				title: "修改头像",
				cancel: "取消",
				buttons: upts
			}, function(opps) {
				switch(opps.index) {
					case 0:
						break;
					case 1:
						getImage();
						break;
					case 2:
						galleryImg();
						break;
					default:
						break
				}
			})
		}

	});

	//	手机拍照
	function getImage() {
		var camera = plus.camera.getCamera(); //获取手机摄像头对象
		var res = camera.supportedImageResolutions[0];
		var fmt = camera.supportedImageFormats[0];

		//调用拍照操作
		camera.captureImage(function(path) {
			//调用本地文件系统
			plus.io.resolveLocalFileSystemURL(path, function(entry) {

				var filename;
				// 可通过entry对象操作上传的文件文件
				entry.file(function(file) {
					var fileReader = new plus.io.FileReader();
					//	设置
					if(file.name.indexOf('.') > -1) {
						filename = file.name.split('.')[0];
					} else {
						filename = 'v' + new Date().getTime();
					}
				});

				var url = entry.toLocalURL() + "?version=" + new Date().getTime();
				var path = plus.io.convertLocalFileSystemURL(url); //转换为平台相对路径
				cuttingImg(path);
			}, function(error) {
				mui.toast('没有选择图片');
			});
		}, function(error) {
			mui.toast('拍照失败');
		}, {
			resolution: res,
			format: fmt
		})

	}

	//	相册选择图片
	function galleryImg() {
		plus.gallery.pick(function(path) {
			cuttingImg(path);
		}, function(err) {
			mui.toast('取消选择');
			var code = err.code; // 错误编码
			var message = err.message; // 错误描述信息
			console.log('图片选择错误编码：' + code);
			console.log('错误信息：' + message);
		}, { //文件过滤，只能筛选图片文件
			filter: 'image',
			multiple: false
		})
	}

	$modal.on('shown.bs.modal', function() {
		cropper = new Cropper(image, {
			aspectRatio: 1,
			viewMode: 3,
		});
	}).on('hidden.bs.modal', function() {
		cropper.destroy();
		cropper = null;
	});

	//	裁剪头像
	function cuttingImg(path) {
		var done = function(url) {
			document.getElementById("image").src = url;
			$modal.modal('show');
		};
		done(path);
	}

	//	裁剪后保存操作
	document.getElementById('crop').addEventListener('click', function() {
		var canvas;

		if(cropper) {
			canvas = cropper.getCroppedCanvas({
				width: 960,
				height: 960,
			});

			//initialAvatarURL = avatar.src;
			var mpicurl = canvas.toDataURL();
			//avatar.src = canvas.toDataURL();

			baseImgFile(userinfo.id, mpicurl, 10, function(r) {
				//console.log('r.target:' + r.target);
				//	图片上传
				var uploadObj = plus.uploader.createUpload(config.getUpload, {
					method: 'post',
					blocksize: '204800',
				}, function(r, status) {
					if(status == 200) {
						mui.toast('头像剪切成功');
						document.getElementById("head-img1").src = JSON.parse(r.responseText).data[0].accessUrl; //更换头像
						avatar.src = JSON.parse(r.responseText).data[0].accessUrl;
						userinfo.avatar = JSON.parse(r.responseText).data[0].relativePath;
					} else {
						console.log("Upload failed: " + status);
					}
				});

				uploadObj.addFile(r.target, {
					key: 'filename'
				});
				uploadObj.start();
			})

			/*canvas.toBlob(function(blob) {
				var formData = new FormData();
				formData.append('avatar', blob);
			});*/

		}

		setTimeout(function() {
			$modal.modal('hide');
		}, 500);
	});

	// base64保存为文件
	function baseImgFile(uid, base64, quality, callback) {
		quality = quality || 10;
		callback = callback || $.noop;
		var bitmap = new plus.nativeObj.Bitmap();
		// 从本地加载Bitmap图片 
		bitmap.loadBase64Data(base64, function() {
			bitmap.save("downloads/" + uid + ".jpg", {
				overwrite: true,
				quality: quality
			}, function(r) {
				callback(r);
			}, function(e) {
				console.log('保存图片失败：' + JSON.stringify(e));
			});
		}, function(e) {
			console.log('加载图片失败：' + JSON.stringify(e));
		});
	}

	//	检测文本框数据是否为空、比对输入的信息与当前登陆的用户信息提示用户是否确认更改
	function checkInput() {

		var flag = false;
		var fuserinfo = app.getUserInfo();
		userinfo.company = document.getElementById('company').value == '' ? null : document.getElementById('company').value;
		userinfo.post = document.getElementById('post').value == '' ? null : document.getElementById('post').value;
		userinfo.deptName = document.getElementById('dept').value == '' ? null : document.getElementById('dept').value;
		userinfo.partyDeptName = document.getElementById('partyDept').value == '' ? null : document.getElementById('partyDept').value;

		if(fuserinfo.avatar != userinfo.avatar || fuserinfo.company != userinfo.company || fuserinfo.deptName != userinfo.deptName || fuserinfo.partyDeptName != userinfo.partyDeptName || fuserinfo.post != userinfo.post) {
			flag = true;
		}
		return flag;
	};

	//	提交更新数据
	function updataInfo() {
		var isInput = checkInput();
		if(!isInput) {
			setTimeout(function() {
				if(wait) {
					wait.close();
				}
				mui.toast('资料无任何修改，无需保存');
			}, 500);
			return;
		}
		wait = plus.nativeUI.showWaiting("更新中...");
		userinfo.dept = userinfo.dept == null ? '' : userinfo.dept;
		userinfo.partyDept = userinfo.partyDept == null ? '' : userinfo.partyDept;

		var updateuserinfo = {
			'id': userinfo.id,
			'avatar': userinfo.avatar,
			'company': userinfo.company,
			'dept': userinfo.dept,
			'partyDept': userinfo.partyDept,
			'post': userinfo.post,

		}

		//	更新用户数据信息
		server.user.saveUserInfo(updateuserinfo, function(r) {
			if(r.errCode == 0) {
				var userInfoobj = {
					"mobile": userinfo.mobile
				}
				//	获取用户信息并存到本地
				server.user.setUserInfo(userInfoobj, function(r) {
					if(r.errCode == 0) {
						localStorage.setItem('userinfo', JSON.stringify(r.data));
					}
				}, function(r) {
					mui.toast("服务器错误，请稍后刷新重试");
				});

				var page = plus.webview.getWebviewById('tab-webview-subsetting.html');
				mui.fire(page, 'myfresh');
				setTimeout(function() {
						wait.close();
						mui.toast('资料已更新');
						mui.back();
					},
					1000)
			} else {
				wait.close();
				mui.toast(e.rrMsg);
			}
		}, function(error) {
			wait.close();
			console.log("r:" + JSON.stringify(error));
			mui.toast('服务器错误,请稍后刷新重试');
		})
	};
})();